package cn.jingdalei.basic.controller;

import cn.jingdalei.basic.util.AjaxResult;
import cn.jingdalei.basic.util.FastDfsUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/dfs")
public class FastDfsController {

    /**
     * @RequestPart 单文件上传
     * required = true 必须产参数 否则报错
     * @param file
     * @return
     */
    @PostMapping
    public AjaxResult upload(@RequestPart(required = true,value="file")
                                         MultipartFile file){
        try {
            // 获取原文件名
            String filename = file.getOriginalFilename();// xxx.jpg
            // 获取后缀 jpg
            String extName = filename.substring(filename.lastIndexOf(".") + 1);
            String uploadPath = FastDfsUtil.upload(file.getBytes(), extName);
            // 返回上传的路径
            return AjaxResult.me().setResultObj(uploadPath);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("上传失败");
        }
    }

    /**
     * 删除文件
     * @param path
     * @return
     */
    @DeleteMapping
    public AjaxResult delFile(@RequestParam(required = true,value = "path")
                              String path){
        try {
            // /goup1/xxxxx/yyyy
            String pathTmp = path.substring(1); // goup1/xxxxx/yyyy
            String groupName =  pathTmp.substring(0, pathTmp.indexOf("/")); // goup1
            String remotePath = pathTmp.substring(pathTmp.indexOf("/")+1); // /xxxxx/yyyy
            FastDfsUtil.delete(groupName, remotePath);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("删除失败");
        }
    }
}
